﻿Imports System.IO
Public Class StateWriter
    Implements IDisposable
    Private _Info As CompilerInfo
    Public ReadOnly Property Info As CompilerInfo
        Get
            Return _Info
        End Get
    End Property
    Public Sub New(Info As CompilerInfo)
        _Info = Info
    End Sub
    Public Sub WriteState(Obj As Object, Wrt As TextWriter)
        'Initializing...
        Info.Tabs = ""
        For Each p As TypeProvider In Info.TypeProviders.Values
            p.Initialize(Info, Nothing, Wrt)
        Next
        'Serializing
        SerializeInternal(Obj, Wrt)
        'Finalizing
        For Each p As TypeProvider In Info.TypeProviders.Values
            p.Finalize()
        Next
        Info.ClearCache()
    End Sub
    Public Sub SerializeInternal(Obj As Object, Wrt As TextWriter)
        'If Object is null write null char and exit
        If Obj Is Nothing Then
            Wrt.Write(Info.Null)
            Exit Sub
        End If
        'else find provider
        Dim Typ = Obj.GetType
        Dim Prvd = Info.FindProvider(Typ)
        'If provider is null throw exception
        If Prvd Is Nothing Then
            Throw New Exception("Provider Not Found")
        End If
        'check waether object exists in cache or not
        If Info.CacheContains(Obj) Then
            Prvd.Write(Info.ObjectId + Info.CacheID(Obj).ToString)
            If Info.Format Then Prvd.WriteLine()
            Exit Sub
        End If
        'else start writing object
        Prvd.WriteType(Typ)
        'writing object
        Prvd.StartBlock()
        Prvd.WriteObject(Obj)
        Prvd.EndBlock()
    End Sub
#Region "IDisposable Support"
    Private disposedValue As Boolean
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
            End If
            _Info = Nothing
        End If
        Me.disposedValue = True
    End Sub
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region
End Class
